package com.ruoyi.socket.gateway;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;

/***
 *  @description
 *  @author zhao
 *  @date: 2020/6/15
 *  @version: v1.0
 */
public class SessionManager {


    // 所有的连接上的socket句柄池
    private static final ConcurrentHashMap<String, SocketChannel> allSocketPolls = new ConcurrentHashMap();
    private static final ConcurrentHashMap<String, SocketChannel> broadcastPolls = new ConcurrentHashMap();

    // 广播用的socket句柄
    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup("ChannelGroups", GlobalEventExecutor.INSTANCE);


    public static SocketChannel add2AllSockets(SocketChannel socketChannel) {
        String sessionId = socketChannel.id().asLongText();
        synchronized (allSocketPolls) {
            allSocketPolls.put(sessionId, socketChannel);
        }
        return socketChannel;
    }

    public static SocketChannel add2BroadSockets(SocketChannel socketChannel) {
        String sessionId = socketChannel.id().asLongText();
        synchronized (broadcastPolls) {
            broadcastPolls.put(sessionId, socketChannel);
            CHANNEL_GROUP.add(socketChannel);
        }
        return socketChannel;
    }


    public static boolean isSession(String sessionID) {
        return allSocketPolls.containsKey(sessionID);
    }


    /***
     * 从all组移除
     * @param channel
     * @return
     */
    public static boolean discard2AllSockets(SocketChannel channel) {
        String sessionId = channel.id().asLongText();
        allSocketPolls.remove(sessionId);
        return true;
    }

    /**
     * 从广播组移除
     *
     * @param channel
     * @return
     */
    public static boolean discard2BroadSockets(SocketChannel channel) {
        String sessionId = channel.id().asLongText();
        broadcastPolls.remove(sessionId);
        return CHANNEL_GROUP.remove(channel);
    }

    /**
     * 广播
     *
     * @param msg
     * @param matcher
     * @return
     */
    public static ChannelGroupFuture broadcast(Object msg, ChannelMatcher matcher) {
        return CHANNEL_GROUP.writeAndFlush(msg, matcher);
    }
}
